<template>
  <div class="app-container">
    <el-container>
      <el-main>
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <!-- 知识库管理 -->
          <el-tab-pane label="知识库管理" name="knowledge-base">
            <div class="top">
              <el-row>
                <el-col :span="12">
                  <el-input
                    v-model="knowledgeBaseQuery.kw"
                    placeholder="搜索知识库名称、描述、标签"
                    style="width: 350px"
                    @keyup.enter.native="searchKnowledgeBase"
                  >
                    <el-button slot="append" icon="el-icon-search" @click="searchKnowledgeBase" />
                  </el-input>
                  <el-select v-model="knowledgeBaseQuery.status" placeholder="状态" clearable style="margin-left: 10px; width: 120px;">
                    <el-option label="活跃" value="active" />
                    <el-option label="未激活" value="inactive" />
                    <el-option label="构建中" value="building" />
                    <el-option label="错误" value="error" />
                  </el-select>
                  <el-input
                    v-model="knowledgeBaseQuery.category"
                    placeholder="分类"
                    style="width: 120px; margin-left: 10px"
                    clearable
                  />
                </el-col>
                <el-col :span="12">
                  <el-button
                    v-if="hasUserPermission"
                    class="add-btn"
                    type="primary"
                    @click="showKnowledgeBaseDialog"
                  >
                    新建知识库
                  </el-button>
                </el-col>
              </el-row>
            </div>

            <!-- 知识库列表 -->
            <el-table
              v-loading="knowledgeBaseLoading"
              :data="knowledgeBaseList"
              border
              style="width: 100%"
            >
              <el-table-column prop="name" label="知识库名称" min-width="150">
                <template slot-scope="scope">
                  <el-link type="primary" @click="viewKnowledgeBaseDetail(scope.row)">
                    {{ scope.row.name }}
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="描述" min-width="100" show-overflow-tooltip />
              <el-table-column prop="category" label="分类" width="100" />
              <el-table-column prop="status" label="状态" width="100">
                <template slot-scope="scope">
                  <el-tag
                    :type="scope.row.status === 'active' ? 'success' :
                      scope.row.status === 'building' ? 'warning' :
                      scope.row.status === 'error' ? 'danger' : 'info'"
                  >
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="document_count" label="文档数量" width="100" />
              <el-table-column prop="tag_list" label="标签"">
                <template slot-scope="scope">
                  <el-tag
                    v-for="tag in getFilteredTags(scope.row.tag_list)"
                    :key="tag"
                    size="mini"
                    style="margin-right: 5px;"
                  >
                    {{ tag }}
                  </el-tag>
                  <span v-if="getFilteredTags(scope.row.tag_list).length === 0" style="color: #999;">无标签</span>
                </template>
              </el-table-column>
              <el-table-column prop="create_at" label="创建时间" width="150">
                <template slot-scope="scope">
                  {{ formatDate(scope.row.create_at) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="250" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    v-if="hasUserPermission"
                    size="mini"
                    @click="editKnowledgeBase(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    size="mini"
                    @click="manageDocuments(scope.row)"
                  >
                    文档管理
                  </el-button>
                  <el-button
                    v-if="hasUserPermission"
                    size="mini"
                    type="danger"
                    @click="deleteKnowledgeBase(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
              v-show="knowledgeBaseTotal > 0"
              background
              :current-page="knowledgeBaseQuery.page"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="knowledgeBaseQuery.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="knowledgeBaseTotal"
              class="mt-pagination"
              @size-change="handleKnowledgeBaseSizeChange"
              @current-change="handleKnowledgeBasePageChange"
            />
          </el-tab-pane>

          <!-- 文档管理 -->
          <el-tab-pane label="文档管理" name="document-management" :disabled="!currentKnowledgeBase">
            <div v-if="currentKnowledgeBase">
              <div class="top">
                <el-row>
                  <el-col :span="12">
                    <h3>{{ currentKnowledgeBase.name }} - 文档管理</h3>
                    <el-input
                      v-model="documentQuery.kw"
                      placeholder="搜索文档名称、备注"
                      style="width: 350px; margin-top: 10px;"
                      @keyup.enter.native="searchDocuments"
                    >
                      <el-button slot="append" icon="el-icon-search" @click="searchDocuments" />
                    </el-input>
                  </el-col>
                  <el-col :span="12">
                    <el-button
                      v-if="hasUserPermission"
                      class="add-btn"
                      type="primary"
                      @click="showUploadDialog"
                    >
                      上传文档
                    </el-button>
                    <el-button
                      v-if="hasUserPermission"
                      class="add-btn"
                      type="success"
                      style="margin-right: 10px;"
                      @click="showUploadUrlDialog"
                    >
                      添加URL
                    </el-button>
                  </el-col>
                </el-row>
              </div>

              <!-- 文档列表 -->
              <el-table
                v-loading="documentLoading"
                :data="documentList"
                border
                style="width: 100%"
              >
                <el-table-column prop="document_name" label="文档名称" min-width="200" />
                <el-table-column prop="document_url" label="文档链接" min-width="300" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <el-link type="primary" :href="scope.row.document_url" target="_blank">
                      {{ scope.row.document_url }}
                    </el-link>
                  </template>
                </el-table-column>
                <el-table-column prop="is_processed" label="处理状态" width="100">
                  <template slot-scope="scope">
                    <el-tag :type="scope.row.is_processed ? 'success' : 'warning'">
                      {{ scope.row.is_processed ? '已处理' : '处理中' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="note" label="备注" min-width="150" show-overflow-tooltip />
                <el-table-column prop="create_at" label="创建时间" width="150">
                  <template slot-scope="scope">
                    {{ formatDate(scope.row.create_at) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right">
                  <template slot-scope="scope">
                    <el-button
                      v-if="hasUserPermission"
                      size="mini"
                      type="danger"
                      @click="deleteDocument(scope.row)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 文档分页 -->
              <el-pagination
                v-show="documentTotal > 0"
                background
                :current-page="documentQuery.page"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="documentQuery.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="documentTotal"
                class="mt-pagination"
                @size-change="handleDocumentSizeChange"
                @current-change="handleDocumentPageChange"
              />
            </div>
            <div v-else style="text-align: center; padding: 50px;">
              <p>请先选择一个知识库</p>
            </div>
          </el-tab-pane>

          <!-- 搜索测试 -->
          <el-tab-pane label="搜索测试" name="search-test" :disabled="!currentKnowledgeBase">
            <div v-if="currentKnowledgeBase">
              <div class="top">
                <h3>{{ currentKnowledgeBase.name }} - 搜索测试</h3>
                <el-row style="margin-top: 20px;">
                  <el-col :span="18">
                    <el-input
                      v-model="searchQuery.query"
                      placeholder="请输入搜索内容"
                      :disabled="searchLoading"
                      @keyup.enter.native="performSearch"
                    >
                      <el-button
                        slot="append"
                        type="primary"
                        :loading="searchLoading"
                        @click="performSearch"
                      >
                        搜索
                      </el-button>
                    </el-input>
                  </el-col>
                  <el-col :span="6" style="padding-left: 10px;">
                    <el-input-number
                      v-model="searchQuery.limit"
                      :min="1"
                      :max="20"
                      label="结果数量"
                      style="width: 100px;"
                    />
                    <el-input-number
                      v-model="searchQuery.score_threshold"
                      :min="0"
                      :max="1"
                      :step="0.1"
                      label="相似度阈值"
                      style="width: 120px; margin-left: 10px;"
                    />
                  </el-col>
                </el-row>
              </div>

              <!-- 搜索结果 -->
              <div v-if="searchLoading || searchTaskId" style="text-align: center; padding: 30px;">
                <el-icon class="is-loading"><i class="el-icon-loading" /></el-icon>
                <p>搜索中，请稍等...</p>
              </div>
              <div v-else-if="searchResults.length > 0" style="margin-top: 20px;">
                <h4>搜索结果：</h4>
                <el-card
                  v-for="(result, index) in searchResults"
                  :key="index"
                  style="margin-bottom: 10px;"
                  shadow="hover"
                >
                  <div slot="header">
                    <span>{{ result.document_name }}</span>
                    <el-tag style="float: right;" type="info">相似度: {{ result.score.toFixed(3) }}</el-tag>
                  </div>
                  <p>{{ result.content }}</p>
                </el-card>
              </div>
              <div v-else-if="searchPerformed" style="text-align: center; padding: 50px;">
                <p>未找到相关结果</p>
              </div>
            </div>
            <div v-else style="text-align: center; padding: 50px;">
              <p>请先选择一个知识库</p>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>

    <!-- 知识库编辑对话框 -->
    <el-dialog
      :title="knowledgeBaseForm.id ? '编辑知识库' : '新建知识库'"
      :visible.sync="knowledgeBaseDialogVisible"
      width="600px"
      class="mt-dialog"
    >
      <el-form ref="knowledgeBaseForm" :model="knowledgeBaseForm" :rules="knowledgeBaseRules" label-width="120px">
        <el-form-item label="知识库名称" prop="name">
          <el-input v-model="knowledgeBaseForm.name" placeholder="请输入知识库名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="knowledgeBaseForm.description"
            type="textarea"
            placeholder="请输入知识库描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="分类">
          <el-input v-model="knowledgeBaseForm.category" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="标签">
          <el-tag
            v-for="tag in knowledgeBaseForm.tag_list"
            :key="tag"
            closable
            style="margin-right: 10px;"
            @close="removeTag(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            size="small"
            style="width: 90px;"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else size="small" @click="showInput">+ 新标签</el-button>
        </el-form-item>
        <el-form-item label="向量维度">
          <el-input-number v-model="knowledgeBaseForm.vector_dimension" :min="128" :max="4096" :step="128" />
        </el-form-item>
        <el-form-item label="嵌入模型">
          <el-select v-model="knowledgeBaseForm.embedding_model" placeholder="请选择嵌入模型">
            <el-option label="jina-embeddings-v3" value="jina-embeddings-v3" />
            <el-option label="text-embedding-ada-002" value="text-embedding-ada-002" />
            <el-option label="text-embedding-3-small" value="text-embedding-3-small" />
            <el-option label="text-embedding-3-large" value="text-embedding-3-large" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="knowledgeBaseForm.status" placeholder="请选择状态">
            <el-option label="活跃" value="active" />
            <el-option label="未激活" value="inactive" />
            <el-option label="构建中" value="building" />
            <el-option label="错误" value="error" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="knowledgeBaseForm.note"
            type="textarea"
            placeholder="请输入备注"
            :rows="2"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="knowledgeBaseDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="knowledgeBaseSaving" @click="saveKnowledgeBase">确定</el-button>
      </div>
    </el-dialog>

    <!-- 文档上传对话框 -->
    <el-dialog
      title="上传文档"
      :visible.sync="uploadDialogVisible"
      width="500px"
      class="mt-dialog"
    >
      <el-upload
        ref="upload"
        :action="uploadAction"
        :headers="uploadHeaders"
        :data="uploadData"
        :before-upload="beforeUpload"
        :on-success="onUploadSuccess"
        :on-error="onUploadError"
        :file-list="fileList"
        :auto-upload="false"
        accept=".pdf,.doc,.docx,.txt,.md"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传 pdf/doc/docx/txt/md 文件，且不超过10MB</div>
      </el-upload>
      <el-form style="margin-top: 20px;">
        <el-form-item label="备注">
          <el-input v-model="uploadForm.note" placeholder="请输入文档备注" />
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- URL上传对话框 -->
    <el-dialog
      title="添加URL文档"
      :visible.sync="uploadUrlDialogVisible"
      width="500px"
      class="mt-dialog"
    >
      <el-form ref="uploadUrlForm" :model="uploadUrlForm" :rules="uploadUrlRules" label-width="100px">
        <el-form-item label="文档URL" prop="url">
          <el-input v-model="uploadUrlForm.url" placeholder="请输入文档URL" />
        </el-form-item>
        <el-form-item label="文档名称">
          <el-input v-model="uploadUrlForm.document_name" placeholder="可选，留空则自动从URL提取" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="uploadUrlForm.note" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadUrlDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="uploadUrlLoading" @click="uploadUrl">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getVectorKnowledgeBaseList,
  createVectorKnowledgeBase,
  updateVectorKnowledgeBase,
  deleteVectorKnowledgeBase,
  getDocuments,
  deleteDocument,
  uploadUrl,
  searchKnowledgeBase,
  getSearchResultByTaskId
} from '@/api/chatbot/knowledge-base'
import { getToken } from '@/utils/auth'

export default {
  name: 'VectorKnowledgeBase',
  data() {
    return {
      activeName: 'knowledge-base',

      // 知识库相关
      knowledgeBaseList: [],
      knowledgeBaseTotal: 0,
      knowledgeBaseLoading: false,
      knowledgeBaseQuery: {
        page: 1,
        pagesize: 10,
        kw: '',
        status: '',
        category: ''
      },
      currentKnowledgeBase: null,

      // 知识库编辑
      knowledgeBaseDialogVisible: false,
      knowledgeBaseSaving: false,
      knowledgeBaseForm: {
        id: null,
        name: '',
        description: '',
        category: '',
        tag_list: [],
        vector_dimension: 1024,
        embedding_model: 'jina-embeddings-v3',
        status: 'active',
        note: ''
      },
      knowledgeBaseRules: {
        name: [
          { required: true, message: '请输入知识库名称', trigger: 'blur' }
        ]
      },
      inputVisible: false,
      inputValue: '',

      // 文档相关
      documentList: [],
      documentTotal: 0,
      documentLoading: false,
      documentQuery: {
        page: 1,
        pagesize: 10,
        kw: ''
      },

      // 文档上传
      uploadDialogVisible: false,
      uploadAction: '',
      uploadHeaders: {},
      uploadData: {},
      uploadForm: {
        note: ''
      },
      fileList: [],

      // URL上传
      uploadUrlDialogVisible: false,
      uploadUrlLoading: false,
      uploadUrlForm: {
        url: '',
        document_name: '',
        note: ''
      },
      uploadUrlRules: {
        url: [
          { required: true, message: '请输入文档URL', trigger: 'blur' }
        ]
      },

      // 搜索相关
      searchQuery: {
        query: '',
        limit: 10,
        score_threshold: 0.7
      },
      searchResults: [],
      searchPerformed: false,
      searchLoading: false,
      searchTaskId: null
    }
  },

  computed: {
    // 权限检查计算属性
    hasUserPermission() {
      try {
        return this.$store && this.$store.getters && this.$store.getters.roles &&
               (this.$store.getters.roles.indexOf('chatbot_user') !== -1 ||
                this.$store.getters.roles.indexOf('admin') !== -1)
      } catch (error) {
        console.warn('权限检查出错:', error)
        return false
      }
    }
  },

  created() {
    // 延迟执行，确保store已初始化
    this.$nextTick(() => {
      this.loadKnowledgeBaseList()
      this.setupUpload()
    })
  },

  methods: {
    // Tab切换
    handleTabClick(tab) {
      if (tab.name === 'document-management' && this.currentKnowledgeBase) {
        this.loadDocuments()
      }
    },

    // 知识库管理
    loadKnowledgeBaseList() {
      this.knowledgeBaseLoading = true
      const params = {
        page: this.knowledgeBaseQuery.page,
        pagesize: this.knowledgeBaseQuery.pagesize,
        kw: this.knowledgeBaseQuery.kw,
        status: this.knowledgeBaseQuery.status,
        category: this.knowledgeBaseQuery.category
      }

      const queryString = Object.keys(params)
        .filter(key => params[key] !== '' && params[key] !== null && params[key] !== undefined)
        .map(key => `${key}=${encodeURIComponent(params[key])}`)
        .join('&')

      getVectorKnowledgeBaseList(queryString)
        .then(response => {
          if (response.success) {
            this.knowledgeBaseList = response.data.data
            this.knowledgeBaseTotal = response.data.total
          } else {
            this.$message.error(response.msg || '获取知识库列表失败')
          }
        })
        .catch(error => {
          this.$message.error('加载知识库列表失败')
          console.error('知识库列表加载错误:', error)
        })
        .finally(() => {
          this.knowledgeBaseLoading = false
        })
    },

    searchKnowledgeBase() {
      this.knowledgeBaseQuery.page = 1
      this.loadKnowledgeBaseList()
    },

    handleKnowledgeBaseSizeChange(val) {
      this.knowledgeBaseQuery.pagesize = val
      this.knowledgeBaseQuery.page = 1
      this.loadKnowledgeBaseList()
    },

    handleKnowledgeBasePageChange(val) {
      this.knowledgeBaseQuery.page = val
      this.loadKnowledgeBaseList()
    },

    showKnowledgeBaseDialog() {
      this.knowledgeBaseForm = {
        id: null,
        name: '',
        description: '',
        category: '',
        tag_list: [],
        vector_dimension: 1024,
        embedding_model: 'jina-embeddings-v3',
        status: 'active',
        note: ''
      }
      this.knowledgeBaseDialogVisible = true
    },

    editKnowledgeBase(row) {
      this.knowledgeBaseForm = {
        id: row.id,
        name: row.name,
        description: row.description || '',
        category: row.category || '',
        tag_list: this.getFilteredTags(row.tag_list || []),
        vector_dimension: row.vector_dimension || 1024,
        embedding_model: row.embedding_model || 'jina-embeddings-v3',
        status: row.status || 'active',
        note: row.note || ''
      }
      this.knowledgeBaseDialogVisible = true
    },

    saveKnowledgeBase() {
      this.$refs.knowledgeBaseForm.validate((valid) => {
        if (valid) {
          this.knowledgeBaseSaving = true
          const formData = {
            ...this.knowledgeBaseForm,
            tags: this.knowledgeBaseForm.tag_list // 发送给后端使用tags参数
          }
          // 删除tag_list，避免重复发送
          delete formData.tag_list

          const promise = this.knowledgeBaseForm.id
            ? updateVectorKnowledgeBase(this.knowledgeBaseForm.id, formData)
            : createVectorKnowledgeBase(formData)

          promise
            .then(response => {
              if (response.success) {
                this.$message.success(this.knowledgeBaseForm.id ? '更新成功' : '创建成功')
                this.knowledgeBaseDialogVisible = false
                this.loadKnowledgeBaseList()
              }
            })
            .catch(error => {
              this.$message.error('操作失败')
              console.error(error)
            })
            .finally(() => {
              this.knowledgeBaseSaving = false
            })
        }
      })
    },

    deleteKnowledgeBase(row) {
      this.$confirm(`确定要删除知识库"${row.name}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteVectorKnowledgeBase(row.id)
          .then(response => {
            if (response.success) {
              this.$message.success('删除成功')
              if (this.currentKnowledgeBase && this.currentKnowledgeBase.id === row.id) {
                this.currentKnowledgeBase = null
              }
              this.loadKnowledgeBaseList()
            }
          })
          .catch(error => {
            this.$message.error('删除失败')
            console.error(error)
          })
      })
    },

    viewKnowledgeBaseDetail(row) {
      this.currentKnowledgeBase = row
      this.activeName = 'document-management'
      this.loadDocuments()
    },

    manageDocuments(row) {
      this.currentKnowledgeBase = row
      this.activeName = 'document-management'
      this.loadDocuments()
    },

    // 标签管理
    removeTag(tag) {
      this.knowledgeBaseForm.tag_list.splice(this.knowledgeBaseForm.tag_list.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue && this.knowledgeBaseForm.tag_list.indexOf(inputValue) === -1) {
        this.knowledgeBaseForm.tag_list.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },

    // 文档管理
    loadDocuments() {
      if (!this.currentKnowledgeBase) return

      this.documentLoading = true
      const params = {
        page: this.documentQuery.page,
        pagesize: this.documentQuery.pagesize,
        kw: this.documentQuery.kw
      }

      const queryString = Object.keys(params)
        .filter(key => params[key] !== '' && params[key] !== null && params[key] !== undefined)
        .map(key => `${key}=${encodeURIComponent(params[key])}`)
        .join('&')

      getDocuments(this.currentKnowledgeBase.id, queryString)
        .then(response => {
          if (response.success) {
            this.documentList = response.data.documents
            this.documentTotal = response.data.total
          }
        })
        .catch(error => {
          this.$message.error('加载文档列表失败')
          console.error(error)
        })
        .finally(() => {
          this.documentLoading = false
        })
    },

    searchDocuments() {
      this.documentQuery.page = 1
      this.loadDocuments()
    },

    handleDocumentSizeChange(val) {
      this.documentQuery.pagesize = val
      this.documentQuery.page = 1
      this.loadDocuments()
    },

    handleDocumentPageChange(val) {
      this.documentQuery.page = val
      this.loadDocuments()
    },

    deleteDocument(row) {
      this.$confirm(`确定要删除文档"${row.document_name}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDocument(this.currentKnowledgeBase.id, row.id)
          .then(response => {
            if (response.success) {
              this.$message.success('删除成功')
              this.loadDocuments()
            }
          })
          .catch(error => {
            this.$message.error('删除失败')
            console.error(error)
          })
      })
    },

    // 文件上传
    setupUpload() {
      const token = getToken()
      this.uploadHeaders = {
        'Authorization': token,
        'ptoken': this.$store.getters.projectId
      }
    },

    showUploadDialog() {
      if (!this.currentKnowledgeBase) {
        this.$message.warning('请先选择知识库')
        return
      }
      this.uploadAction = process.env.VUE_APP_BASE_API + `/chatbot/api/vector-knowledge-base/${this.currentKnowledgeBase.id}/upload-document/`
      this.uploadForm.note = ''
      this.fileList = []
      this.uploadDialogVisible = true
    },

    beforeUpload(file) {
      const isValidType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain', 'text/markdown'].includes(file.type)
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isValidType) {
        this.$message.error('只能上传 PDF/DOC/DOCX/TXT/MD 格式的文件!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
        return false
      }
      return true
    },

    submitUpload() {
      this.uploadData = {
        note: this.uploadForm.note
      }
      this.$refs.upload.submit()
    },

    onUploadSuccess(response) {
      if (response.success) {
        this.$message.success('文档上传成功')
        this.uploadDialogVisible = false
        this.loadDocuments()
      } else {
        this.$message.error(response.msg || '上传失败')
      }
    },

    onUploadError(error) {
      this.$message.error('文档上传失败')
      console.error(error)
    },

    // URL上传
    showUploadUrlDialog() {
      if (!this.currentKnowledgeBase) {
        this.$message.warning('请先选择知识库')
        return
      }
      this.uploadUrlForm = {
        url: '',
        document_name: '',
        note: ''
      }
      this.uploadUrlDialogVisible = true
    },

    uploadUrl() {
      this.$refs.uploadUrlForm.validate((valid) => {
        if (valid) {
          this.uploadUrlLoading = true
          uploadUrl(this.currentKnowledgeBase.id, this.uploadUrlForm)
            .then(response => {
              if (response.success) {
                this.$message.success('URL文档添加成功')
                this.uploadUrlDialogVisible = false
                this.loadDocuments()
              }
            })
            .catch(error => {
              this.$message.error('添加失败')
              console.error(error)
            })
            .finally(() => {
              this.uploadUrlLoading = false
            })
        }
      })
    },

    // 搜索测试
    performSearch() {
      if (!this.currentKnowledgeBase) {
        this.$message.warning('请先选择知识库')
        return
      }

      if (!this.searchQuery.query.trim()) {
        this.$message.warning('请输入搜索内容')
        return
      }

      this.searchLoading = true
      this.searchResults = []
      this.searchPerformed = false

      searchKnowledgeBase(this.currentKnowledgeBase.id, this.searchQuery)
        .then(response => {
          if (response.success) {
            if (response.data.results) {
              // 直接返回搜索结果
              this.searchResults = response.data.results
              this.searchPerformed = true
              if (this.searchResults.length === 0) {
                this.$message.info('未找到相关结果')
              }
            } else if (response.data.task_id) {
              // 异步搜索，需要轮询结果
              this.searchTaskId = response.data.task_id
              this.$message.info('搜索正在进行中，请稍等...')
              this.pollSearchResult()
            }
          }
        })
        .catch(error => {
          this.$message.error('搜索失败')
          console.error(error)
        })
        .finally(() => {
          this.searchLoading = false
        })
    },

    // 轮询搜索结果
    pollSearchResult() {
      if (!this.searchTaskId) return

      const poll = () => {
        getSearchResultByTaskId(this.currentKnowledgeBase.id, this.searchTaskId)
          .then(response => {
            if (response.success) {
              if (response.data.results) {
                // 搜索完成
                this.searchResults = response.data.results
                this.searchPerformed = true
                this.searchTaskId = null
                if (this.searchResults.length === 0) {
                  this.$message.info('未找到相关结果')
                } else {
                  this.$message.success('搜索完成')
                }
              } else if (response.data.status === 'processing') {
                // 仍在处理中，继续轮询
                setTimeout(poll, 2000) // 2秒后再次查询
              }
            }
          })
          .catch(error => {
            this.$message.error('获取搜索结果失败')
            console.error(error)
            this.searchTaskId = null
          })
      }

      // 开始轮询
      setTimeout(poll, 2000)
    },

    // 工具方法
    getStatusText(status) {
      const statusMap = {
        'active': '活跃',
        'inactive': '未激活',
        'building': '构建中',
        'error': '错误'
      }
      return statusMap[status] || status
    },

    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    },

    // 过滤有效的标签
    getFilteredTags(tagList) {
      if (!Array.isArray(tagList)) return []
      return tagList.filter(tag => {
        // 过滤掉空字符串、"[]"、null、undefined
        return tag && tag.trim() && tag !== '[]' && tag !== 'null' && tag !== 'undefined'
      })
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 20px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}
</style>
